//
//  LoginViewController.m
//  Student
//
//  Created by 李飞 on 15/9/8.
//  Copyright (c) 2015年 XueYinYue. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterAgreementViewController.h"
#import "NSString+WPAttributedMarkup.h"
#import "WPAttributedStyleAction.h"
#import <CoreText/CoreText.h>
#import "WPHotspotLabel.h"


#import "UserBSRegister.h"
#import "UIColor+Chains.h"
#import "UserBSGetVerificationCode.h"
#import "MyInfoViewController.h"


@interface RegisterViewController ()
{
    int _timeout;
    dispatch_source_t _timer;
    bool isAgreeRegisterAgreement;
    bool canRegister;
    
    bool isPhoneNull;
    bool identifyCodeNull;
    bool isPasswordNull;
    bool isCheckPasswordNull;
}

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"欢迎加入学音悦";
    //隐藏错误提示信息
    _registerBtn.enabled = NO;
    isAgreeRegisterAgreement = YES;
    canRegister = NO;
    
    _verificationCode = @"";
    isPhoneNull = YES;
    identifyCodeNull = YES;
    isPasswordNull = YES;
    isCheckPasswordNull = YES;
    
    [self.navigationItem setHidesBackButton:YES];

    
    //设置TFplaceholder字体颜色
    [_userNameTF setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_identifyCodeTF setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_passwordTF setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_checkPasswordTF setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
    
    NSDictionary *style = @{@"body":@[[UIFont fontWithName:@"HelveticaNeue" size:17.0],[UIColor blackColor]],
                            @"tap":[WPAttributedStyleAction styledActionWithAction:^{
                                NSLog(@"check protocol");
                            }],
                            @"link":@[[UIColor orangeColor],
                                      @{NSUnderlineStyleAttributeName : @(kCTUnderlineStyleSingle|kCTUnderlinePatternSolid)},
                                      [UIFont fontWithName:@"HelveticaNeue" size:16.0]]};
    _tipsLab.attributedText = [@"同意<tap>学音悦注册协议</tap>" attributedStringWithStyleBook:style];


//   [self initNavegationBar];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 自定义方法
/**
 *  创建改变获取验证码按钮状态的定时器
 */
- (void)createTimer
{
    _timeout = 60;
    dispatch_queue_t queue = dispatch_queue_create("timer queue", 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        if (_timeout > 0)
        {
            _timeout -= 1;
            dispatch_async(dispatch_get_main_queue(), ^{
                [_getVerificationCodeButton setTitle:[NSString stringWithFormat:@"获取验证码(%ds)",_timeout] forState:UIControlStateDisabled];
                [_getVerificationCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                _getVerificationCodeButton.enabled = YES;
                [_getVerificationCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [_getVerificationCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            });
            dispatch_source_cancel(_timer);
        }
    });
    dispatch_source_set_cancel_handler(_timer, ^{
        //        NSLog(@"timer cancle");
        _timer = nil;
    });
    dispatch_resume(_timer);
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    
    if( textField == _userNameTF)
    {
        if (toBeString.length != 0)
        {
            isPhoneNull = NO;
        }
        else
        {
            isPhoneNull = YES;
        }
    }
    
    if ( textField == _identifyCodeTF)
    {
        if (toBeString.length != 0)
        {
            identifyCodeNull = NO;
        }
        else
        {
            identifyCodeNull = YES;
        }
    }
    
    if ( textField == _passwordTF)
    {
        if (toBeString.length != 0)
        {
            isPasswordNull  = NO;
        }
        else
        {
            isPasswordNull = YES;
        }
    }
    if ( textField == _checkPasswordTF)
    {
        if (toBeString.length != 0)
        {
            isCheckPasswordNull  = NO;
        }
        else
        {
            isCheckPasswordNull = YES;
        }
    }
    
    if (isPasswordNull || isPhoneNull || identifyCodeNull || isCheckPasswordNull)
    {
        _registerBtn.enabled = NO;
    }
    else
    {
        _registerBtn.enabled = YES;
    }
    
    return YES;
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - 事件响应
- (IBAction)onReceiveIdentifyingCodeButtonClick:(id)sender {
    
    UserBSGetVerificationCode *userBSGetVerificationCode = [[UserBSGetVerificationCode alloc] init];
    userBSGetVerificationCode.username = _userNameTF.text;
    
    [self showProgressView];
    [self runService:userBSGetVerificationCode andComplete:^(EACService *service) {
        [self hideProgressView];
    } andSuccess:^(EACService *service, id o) {
        UserBSGetVerificationCodeResult* userBSGetVerificationCodeResult = o;
        if (userBSGetVerificationCodeResult.isSuccess)
        {
            _getVerificationCodeButton.enabled = NO;
            _verificationCode = userBSGetVerificationCodeResult.code;
            
            if (!_timer)
            {
                [self createTimer];
            }
        }
        else
        {
            SHOW_ALERTVIEW(@"提示", userBSGetVerificationCodeResult.message, 1, self);
        }
    } ];
    
}

- (IBAction)onShowPasswordClick:(id)sender {
    UIImage *image;
    _passwordTF.secureTextEntry = !_passwordTF.isSecureTextEntry;
    if (_passwordTF.secureTextEntry)
    {
        image = [UIImage imageNamed:@"icon_eye_gray.png"];
    }
    else
    {
        image = [UIImage imageNamed:@"icon_eye_green.png"];
    }
    [_showPasswordBtn setImage:image forState:UIControlStateNormal];
}

- (IBAction)onShowCheckPasswordClick:(id)sender {
    UIImage *image;
    _checkPasswordTF.secureTextEntry = !_checkPasswordTF.isSecureTextEntry;
    if (_checkPasswordTF.secureTextEntry)
    {
        image = [UIImage imageNamed:@"icon_eye_gray.png"];
    }
    else
    {
        image = [UIImage imageNamed:@"icon_eye_green.png"];
    }
    [_showCheckPasswordBtn setImage:image forState:UIControlStateNormal];

}

- (IBAction)onRegisterbuttonClick:(id)sender {
    if ([_passwordTF.text isEqualToString:_checkPasswordTF.text])
    {
        UserBSRegister *userBSRegister = [[UserBSRegister alloc] init];
        userBSRegister.phoneNum = _userNameTF.text;
        userBSRegister.getVerificationCode = _verificationCode;
        userBSRegister.InputVerificationCode = _identifyCodeTF.text;
        userBSRegister.password = _passwordTF.text;
        
        [self showProgressView];
        
        [self runService:userBSRegister
             andComplete:^(EACService *service) {
                 [self hideProgressView];
             }
              andSuccess:^(EACService *service, id o) {
                  UserBSRegisterResult *userBSRegisterResult = o;
                  
                  if (userBSRegisterResult.isRegisterSuccess)
                  {
                      //进入用户信息设置界面
                      MyInfoViewController *myInfoViewController = [[MyInfoViewController alloc] initWithNibName:@"MyInfoViewController" bundle:nil];
                      myInfoViewController.isComeHome = NO;
                      [self.navigationController pushViewController:myInfoViewController animated:YES];
                  }
                  else
                  {
                      SHOW_ALERTVIEW(@"提示",userBSRegisterResult.message, 1, self);
                  }
              }];
    }
    else
    {
        SHOW_ALERTVIEW(@"提示",@"密码输入不一致，请重新输入。", 1, self);
    }
    
}

- (IBAction)onRegisterAgreementClick:(id)sender {
    
    isAgreeRegisterAgreement = !isAgreeRegisterAgreement;
    
    UIImage *image;
    if (isAgreeRegisterAgreement)
    {
        image = [UIImage imageNamed:@"Checkmark_green_pressed"];

        if (canRegister)
        {            
            _registerBtn.enabled = YES;
        }
    }
    else
    {
        image = [UIImage imageNamed:@"Checkmark_gray_normal"];
        _registerBtn.enabled = NO;
    }
    [_registerAgreementBtn setImage:image forState:UIControlStateNormal];
}

#pragma mark -  NavegationBar
- (void)initNavegationBar
{
    
    //    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    //    backBtn.bounds = CGRectMake(0, 0, 15, 20);
    //    [backBtn addTarget:self action:@selector(onBackButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [backBtn setBackgroundImage:[UIImage imageNamed:NAVIGATION_BACKARROW_IMAGE] forState:UIControlStateNormal];
    
    UIBarButtonItem *backBarBtn = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(onBackButtonClick:)];
    self.navigationItem.leftBarButtonItem = backBarBtn;
}


- (void)onBackButtonClick:(id)sender
{
    [ _passwordTF resignFirstResponder];
    [ _userNameTF resignFirstResponder];
    [ _identifyCodeTF resignFirstResponder];
    SHOW_ALERTVIEW_WITH_CANCLE_OK(@"提示", @"是否返回并放弃新用户注册？", 1, self);
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1)
    {
        if (buttonIndex == 1)
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}
- (IBAction)onAgreementBtnClick:(id)sender {
    RegisterAgreementViewController* registerAgreementViewController = [[RegisterAgreementViewController alloc]initWithNibName:@"RegisterAgreementViewController" bundle:nil];
    [self.navigationController pushViewController:registerAgreementViewController animated:YES];
}
@end
